$(function() {

    $(".form-myt-stock-commodity-stock-move-inputBasic").data("formOptions", {
        updateTotalAmount : function() {
            var $form = $(this);

            var $grid = $form.find(".grid-myt-stock-commodity-stock-move-inputBasic");
            var userData = {
                "commodity.display" : "合计："
            };
            // 更新表格汇总统计数据
            userData.quantity = $grid.jqGrid('sumColumn', 'quantity');
            userData.amount = $grid.jqGrid('sumColumn', 'amount');
            userData.deliveryAmount = $grid.jqGrid('sumColumn', 'deliveryAmount');
            $grid.jqGrid("footerData", "set", userData, true);

            var totalDeliveryAmount = Util.parseFloatValDefaultZero($form.find("input[name='totalDeliveryAmount']"));
            var totalCostAmount = MathUtil.add(userData.amount,totalDeliveryAmount);
            $form.setFormDatas({
                totalCostAmount : totalCostAmount,
                totalDeliveryAmount : userData.deliveryAmount
            });
        },
        bindEvents : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-stock-commodity-stock-move-inputBasic");

            // Biz.setupCustomerProfileSelect($form);

            //按金额自动分摊运费
            $form.find(".btn-delivery-by-amount").click(function() {
                if ($grid.jqGrid("isEditingMode", true)) {
                    return false;
                }
                //按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
                var totalDeliveryAmount = $form.find("input[name='totalDeliveryAmount']").val();
                var totalAmount = $grid.jqGrid('sumColumn', 'amount');
                var perDeliveryAmount = MathUtil.div(totalDeliveryAmount, totalAmount, 5);

                var lastrowid = null;
                var tempDeliveryAmount = 0;
                var ids = $grid.jqGrid("getDataIDs");
                $.each(ids, function(i, id) {
                    var rowdata = $grid.jqGrid("getRowData", id);
                    if (rowdata['commodity.id'] != '') {
                        rowdata['deliveryAmount'] = MathUtil.mul(perDeliveryAmount, rowdata['amount']);
                        $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'deliveryAmount');
                        $grid.jqGrid('setRowData', id, rowdata);
                        tempDeliveryAmount = MathUtil.add(tempDeliveryAmount, rowdata['deliveryAmount']);
                        lastrowid = id;
                    }
                });

                //最后一条记录需要以减法计算以修正小数精度问题
                if (lastrowid) {
                    var rowdata = $grid.jqGrid("getRowData", lastrowid);
                    rowdata['deliveryAmount'] = MathUtil.sub(totalDeliveryAmount, MathUtil.sub(tempDeliveryAmount, rowdata['deliveryAmount']));
                    $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'deliveryAmount');
                    $grid.jqGrid('setRowData', lastrowid, rowdata);
                }

                $form.data("formOptions").updateTotalAmount.call($form);

            });

        }

    });

    $(".grid-myt-stock-commodity-stock-move-inputBasic").data("gridOptions", {
        calcRowAmount : function(rowdata, src) {

            rowdata['amount'] = rowdata['price'] * rowdata['quantity'];
            rowdata['costAmount'] = MathUtil.add(rowdata['amount'], rowdata['deliveryAmount']);
            rowdata['costPrice'] = MathUtil.div(rowdata['costAmount'], rowdata['quantity'], 5);
        },
        updateRowAmount : function(src) {
            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);
        },
        batchEntitiesPrefix : "commodityStockMoveDetails",
        url : function() {
            var pk = $(this).attr("data-pk");
            if (pk) {
                return WEB_ROOT + "/myt/stock/commodity-stock-move!commodityStockMoveDetails?id=" + pk + "&clone=" + $(this).attr("data-clone");
            }
        },
        colModel : [ {
            label : '调货主键',
            name : 'commodityStockMove.id',
            hidden : true,
            hidedlg : true,
            editable : true,
            formatter : function(cellValue, options, rowdata, action) {
                var pk = $(this).attr("data-pk");
                return pk ? pk : "";
            }
        }, {
            name : 'commodityStock.id',
            hidden : true,
            hidedlg : true,
            editable : true
        },  {
            name : 'storageLocation.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.sku',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '销售（发货）商品',
            name : 'commodity.display',
            editable : true,
            editrules : {
                required : true
            },
           editoptions : {
                placeholder : '双击选择出发仓库商品',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    var selectCommodityStock = function(item) {
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            console.info("select: "+item['commodity.sku']+" "+item.batchNo+" "+item['storageLocation.id']);
                            console.info("existt: "+row['commodity.sku']+" "+row.batchNo+" "+row['storageLocation.id']);
                            
                            if(item['commodity.sku'] == row['commodity.sku'] && 
                                    item.batchNo == row.batchNo && 
                                    item['storageLocation.id'] == row['storageLocation.id']){
                                     // SKU，批次号，库存地一致即认为是同一商品
                                existRowId = ids[i];
                                oldQuantity = row.quantity;
                                break;
                            }
                        }
                        
                        if(existRowId){
                            $grid.jqGrid("setRowData", existRowId, {
                                'quantity' : MathUtil.add(oldQuantity,1)
                            });
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            $grid.jqGrid("setRowData", existRowId, myrowdata);
                        }else{
                            var myrowdata = {             
                                    'commodity.sku' : item['commodity.sku'],//商品唯一性标识
                                    'commodity.id' : item['commodity.id'],
                                    'commodity.barcode' : item['commodity.barcode'],
                                    'commodity.sku' : item['commodity.sku'],
                                    'commodity.display' : item['commodity.display'],
                                    'commodity.title' : item['commodity.title'],
                                    'price' : item['costPrice'],
                                    'measureUnit' : item['commodity.measureUnit'],
                                    'storageLocation.id' : item['storageLocation.id'],
                                    'batchNo' : item['batchNo'],
                                    'expireDate' : item['expireDate'],
                                    'quantity' : 1,
                                    'discountRate' : 0,
                                    'taxRate' : 0,
                                    'deliveryAmount' : 0
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("insertNewRowdata", myrowdata);
                        }
                        
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                        
                        var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                        $grid.jqGrid('setRowData', existRowId, {
                            subVoucher : 100 + idx * 10
                        });
                    }   
                    $elem.dblclick(function() {
                        var originStorageLocationId =  $(".form-myt-stock-commodity-stock-move-inputBasic select[name='originStorageLocation.id']").val();
                        if(originStorageLocationId==''){
                            alert("清先选择‘出发仓库’");
                        }else{
                             $(this).popupDialog({
                                url : WEB_ROOT + "/myt/stock/commodity-stock!forward?_to_=selection",
                                postData : {
                                    storageLocationId :originStorageLocationId
                                },
                                title : '选取商品',
                                callback : selectCommodityStock
                            })
                        }
                        // 多选模式双击弹出选取框之后，取消当前行编辑状态
                        $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                    });
                   
                }
            },
            align : 'left'
        }, {
            label : '批次号',
            name : 'batchNo',
            width : 80,
            editable : true,
            editoptions : {
                readonly : true
            }
        }, {
            label : '批次过期日期',
            name : 'expireDate',
            width : 80,
            editable : true,
            editoptions : {
                readonly : true
            }
        },{
            label : '单位',
            name : 'measureUnit',
            editable : true,
            width : 80
        }, {
            label : '数量',
            name : 'quantity',
            width : 80,
            formatter : 'number',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            summaryType : 'sum'
        }, {
            label : '成本单价',
            name : 'price',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            summaryType : 'sum'
        }, {
            label : '原始金额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '运费',
            name : 'deliveryAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    if ($elem.val() == "") {
                        $elem.val(0)
                    }
                    var $form = $elem.closest("form");
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '入库成本单价',
            name : 'costPrice',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                readonly : true
            },
            responsive : 'sm'
        }, {
            label : '入库总成本',
            name : 'costAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        userDataOnFooter : true
    });

});